using System;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Text;
using System.Windows.Forms;

using ctsu.Shared;
using ctsu.Data;


namespace ctsu.Admin.Forms
{
	public class FormTestLabelInfo : System.Windows.Forms.Form
	{
		private BarScan _barscan;
		private BarScan.BarScanCompleteHandler _barScanComplete;

		//for printing
		private PrintDialog _pDlg;
		private PrintDocument _pDoc;
		private int _page;
		private int _startRow;
		private DataGrid _dgPrint;
		private DataTable _dtPrint;
		private string _subTitle;

		#region windows controls
		private System.Windows.Forms.GroupBox gbxCheckinType;
		private System.Windows.Forms.Button Retrieve;
		private System.Windows.Forms.TextBox Num_ID;
		private System.Windows.Forms.Label lblNum_ID;
		private Syncfusion.Windows.Forms.Tools.TabControlAdv tabControlAdv1;
		private Syncfusion.Windows.Forms.Tools.TabPageAdv tab1;
		private Syncfusion.Windows.Forms.Tools.TabPageAdv tab2;
		private Syncfusion.Windows.Forms.Tools.TabPageAdv tab3;
		private System.Windows.Forms.DataGrid dgTestIn;
		private System.Windows.Forms.DataGrid dgDraw;
		private Syncfusion.Windows.Forms.Tools.TabPageAdv tab4;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.DataGrid dgTestOut;
		private Syncfusion.Windows.Forms.Tools.TabPageAdv tab5;
		private System.Windows.Forms.DataGrid dgProtocol;
		private System.Windows.Forms.DataGrid dgPatient;
		private System.Windows.Forms.Button btnPrintGrid;
		private System.Windows.Forms.Button btnExit;
		private System.ComponentModel.Container components = null;
		#endregion windows controls

		public FormTestLabelInfo()
		{
			InitializeComponent();
			Num_ID.KeyPress += new KeyPressEventHandler(Utils.txtNumWholePos_KeyPress);

			this._barScanComplete += new BarScan.BarScanCompleteHandler(barScan_Complete);
			this._barscan = new BarScan(this, Num_ID, this._barScanComplete);

		}

		private void barScan_Complete(object sender, BarScanEventArgs e)
		{
			if (e.ID > -1)
				Retrieve_Click(sender, new System.EventArgs());
		}

		private void Num_ID_TextChanged(object sender, System.EventArgs e)
		{
			if (Num_ID.Text.Length > 0)
			{
				if ((Convert.ToInt32(Num_ID.Text)) > 0)
					Retrieve.Enabled = true;
				else
					Retrieve.Enabled = false;
			}
			else
				Retrieve.Enabled = false;
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.gbxCheckinType = new System.Windows.Forms.GroupBox();
			this.Retrieve = new System.Windows.Forms.Button();
			this.Num_ID = new System.Windows.Forms.TextBox();
			this.lblNum_ID = new System.Windows.Forms.Label();
			this.tabControlAdv1 = new Syncfusion.Windows.Forms.Tools.TabControlAdv();
			this.tab1 = new Syncfusion.Windows.Forms.Tools.TabPageAdv();
			this.dgDraw = new System.Windows.Forms.DataGrid();
			this.tab2 = new Syncfusion.Windows.Forms.Tools.TabPageAdv();
			this.dgTestIn = new System.Windows.Forms.DataGrid();
			this.tab3 = new Syncfusion.Windows.Forms.Tools.TabPageAdv();
			this.dgTestOut = new System.Windows.Forms.DataGrid();
			this.label1 = new System.Windows.Forms.Label();
			this.tab4 = new Syncfusion.Windows.Forms.Tools.TabPageAdv();
			this.dgProtocol = new System.Windows.Forms.DataGrid();
			this.tab5 = new Syncfusion.Windows.Forms.Tools.TabPageAdv();
			this.dgPatient = new System.Windows.Forms.DataGrid();
			this.btnPrintGrid = new System.Windows.Forms.Button();
			this.btnExit = new System.Windows.Forms.Button();
			this.gbxCheckinType.SuspendLayout();
			((System.ComponentModel.ISupportInitialize)(this.tabControlAdv1)).BeginInit();
			this.tabControlAdv1.SuspendLayout();
			this.tab1.SuspendLayout();
			((System.ComponentModel.ISupportInitialize)(this.dgDraw)).BeginInit();
			this.tab2.SuspendLayout();
			((System.ComponentModel.ISupportInitialize)(this.dgTestIn)).BeginInit();
			this.tab3.SuspendLayout();
			((System.ComponentModel.ISupportInitialize)(this.dgTestOut)).BeginInit();
			this.tab4.SuspendLayout();
			((System.ComponentModel.ISupportInitialize)(this.dgProtocol)).BeginInit();
			this.tab5.SuspendLayout();
			((System.ComponentModel.ISupportInitialize)(this.dgPatient)).BeginInit();
			this.SuspendLayout();
			// 
			// gbxCheckinType
			// 
			this.gbxCheckinType.Controls.Add(this.Retrieve);
			this.gbxCheckinType.Controls.Add(this.Num_ID);
			this.gbxCheckinType.Controls.Add(this.lblNum_ID);
			this.gbxCheckinType.Location = new System.Drawing.Point(8, 0);
			this.gbxCheckinType.Name = "gbxCheckinType";
			this.gbxCheckinType.Size = new System.Drawing.Size(240, 56);
			this.gbxCheckinType.TabIndex = 3;
			this.gbxCheckinType.TabStop = false;
			// 
			// Retrieve
			// 
			this.Retrieve.Enabled = false;
			this.Retrieve.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
			this.Retrieve.Location = new System.Drawing.Point(168, 24);
			this.Retrieve.Name = "Retrieve";
			this.Retrieve.Size = new System.Drawing.Size(64, 23);
			this.Retrieve.TabIndex = 43;
			this.Retrieve.Text = "Retrieve";
			this.Retrieve.Click += new System.EventHandler(this.Retrieve_Click);
			// 
			// Num_ID
			// 
			this.Num_ID.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
			this.Num_ID.Location = new System.Drawing.Point(104, 24);
			this.Num_ID.MaxLength = 5;
			this.Num_ID.Name = "Num_ID";
			this.Num_ID.Size = new System.Drawing.Size(56, 20);
			this.Num_ID.TabIndex = 0;
			this.Num_ID.TextChanged += new System.EventHandler(this.Num_ID_TextChanged);
			// 
			// lblNum_ID
			// 
			this.lblNum_ID.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
			this.lblNum_ID.Location = new System.Drawing.Point(8, 16);
			this.lblNum_ID.Name = "lblNum_ID";
			this.lblNum_ID.Size = new System.Drawing.Size(96, 32);
			this.lblNum_ID.TabIndex = 44;
			this.lblNum_ID.Text = "Scan barcode or enter label ID:";
			// 
			// tabControlAdv1
			// 
			this.tabControlAdv1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
						| System.Windows.Forms.AnchorStyles.Left)
						| System.Windows.Forms.AnchorStyles.Right)));
			this.tabControlAdv1.Controls.Add(this.tab1);
			this.tabControlAdv1.Controls.Add(this.tab2);
			this.tabControlAdv1.Controls.Add(this.tab3);
			this.tabControlAdv1.Controls.Add(this.tab4);
			this.tabControlAdv1.Controls.Add(this.tab5);
			this.tabControlAdv1.Location = new System.Drawing.Point(8, 64);
			this.tabControlAdv1.Name = "tabControlAdv1";
			this.tabControlAdv1.Size = new System.Drawing.Size(936, 136);
			this.tabControlAdv1.TabIndex = 4;
			// 
			// tab1
			// 
			this.tab1.BackColor = System.Drawing.Color.White;
			this.tab1.Controls.Add(this.dgDraw);
			this.tab1.Location = new System.Drawing.Point(1, 26);
			this.tab1.Name = "tab1";
			this.tab1.Size = new System.Drawing.Size(933, 108);
			this.tab1.TabIndex = 1;
			this.tab1.Text = "Draw Info";
			this.tab1.ThemesEnabled = false;
			// 
			// dgDraw
			// 
			this.dgDraw.DataMember = "";
			this.dgDraw.Dock = System.Windows.Forms.DockStyle.Fill;
			this.dgDraw.HeaderForeColor = System.Drawing.SystemColors.ControlText;
			this.dgDraw.Location = new System.Drawing.Point(0, 0);
			this.dgDraw.Name = "dgDraw";
			this.dgDraw.Size = new System.Drawing.Size(933, 108);
			this.dgDraw.TabIndex = 0;
			// 
			// tab2
			// 
			this.tab2.Controls.Add(this.dgTestIn);
			this.tab2.Location = new System.Drawing.Point(1, 1);
			this.tab2.Name = "tab2";
			this.tab2.Size = new System.Drawing.Size(933, 133);
			this.tab2.TabIndex = 1;
			this.tab2.Text = "Test Check-in Info";
			this.tab2.ThemesEnabled = false;
			// 
			// dgTestIn
			// 
			this.dgTestIn.DataMember = "";
			this.dgTestIn.Dock = System.Windows.Forms.DockStyle.Fill;
			this.dgTestIn.HeaderForeColor = System.Drawing.SystemColors.ControlText;
			this.dgTestIn.Location = new System.Drawing.Point(0, 0);
			this.dgTestIn.Name = "dgTestIn";
			this.dgTestIn.Size = new System.Drawing.Size(933, 133);
			this.dgTestIn.TabIndex = 0;
			// 
			// tab3
			// 
			this.tab3.BackColor = System.Drawing.Color.White;
			this.tab3.Controls.Add(this.dgTestOut);
			this.tab3.Controls.Add(this.label1);
			this.tab3.Location = new System.Drawing.Point(1, 1);
			this.tab3.Name = "tab3";
			this.tab3.Size = new System.Drawing.Size(933, 133);
			this.tab3.TabIndex = 2;
			this.tab3.Text = "Test Check-out Info";
			this.tab3.ThemesEnabled = false;
			// 
			// dgTestOut
			// 
			this.dgTestOut.DataMember = "";
			this.dgTestOut.Dock = System.Windows.Forms.DockStyle.Fill;
			this.dgTestOut.HeaderForeColor = System.Drawing.SystemColors.ControlText;
			this.dgTestOut.Location = new System.Drawing.Point(0, 0);
			this.dgTestOut.Name = "dgTestOut";
			this.dgTestOut.Size = new System.Drawing.Size(933, 133);
			this.dgTestOut.TabIndex = 1;
			// 
			// label1
			// 
			this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
			this.label1.Location = new System.Drawing.Point(16, 16);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(360, 40);
			this.label1.TabIndex = 0;
			this.label1.Text = "Not checked out!";
			// 
			// tab4
			// 
			this.tab4.Controls.Add(this.dgProtocol);
			this.tab4.Location = new System.Drawing.Point(1, 1);
			this.tab4.Name = "tab4";
			this.tab4.Size = new System.Drawing.Size(933, 133);
			this.tab4.TabIndex = 3;
			this.tab4.Text = "Protocol Info";
			this.tab4.ThemesEnabled = false;
			// 
			// dgProtocol
			// 
			this.dgProtocol.DataMember = "";
			this.dgProtocol.Dock = System.Windows.Forms.DockStyle.Fill;
			this.dgProtocol.HeaderForeColor = System.Drawing.SystemColors.ControlText;
			this.dgProtocol.Location = new System.Drawing.Point(0, 0);
			this.dgProtocol.Name = "dgProtocol";
			this.dgProtocol.Size = new System.Drawing.Size(933, 133);
			this.dgProtocol.TabIndex = 0;
			// 
			// tab5
			// 
			this.tab5.Controls.Add(this.dgPatient);
			this.tab5.Location = new System.Drawing.Point(1, 1);
			this.tab5.Name = "tab5";
			this.tab5.Size = new System.Drawing.Size(933, 133);
			this.tab5.TabIndex = 4;
			this.tab5.Text = "Patient Info";
			this.tab5.ThemesEnabled = false;
			// 
			// dgPatient
			// 
			this.dgPatient.DataMember = "";
			this.dgPatient.Dock = System.Windows.Forms.DockStyle.Fill;
			this.dgPatient.HeaderForeColor = System.Drawing.SystemColors.ControlText;
			this.dgPatient.Location = new System.Drawing.Point(0, 0);
			this.dgPatient.Name = "dgPatient";
			this.dgPatient.Size = new System.Drawing.Size(933, 133);
			this.dgPatient.TabIndex = 0;
			// 
			// btnPrintGrid
			// 
			this.btnPrintGrid.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
			this.btnPrintGrid.Location = new System.Drawing.Point(367, 208);
			this.btnPrintGrid.Name = "btnPrintGrid";
			this.btnPrintGrid.Size = new System.Drawing.Size(112, 23);
			this.btnPrintGrid.TabIndex = 5;
			this.btnPrintGrid.Text = "Print Selected Tab";
			this.btnPrintGrid.Click += new System.EventHandler(this.btnPrintGrid_Click);
			// 
			// btnExit
			// 
			this.btnExit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
			this.btnExit.Location = new System.Drawing.Point(511, 208);
			this.btnExit.Name = "btnExit";
			this.btnExit.Size = new System.Drawing.Size(75, 23);
			this.btnExit.TabIndex = 6;
			this.btnExit.Text = "Close";
			this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
			// 
			// FormTestLabelInfo
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(952, 238);
			this.Controls.Add(this.btnExit);
			this.Controls.Add(this.btnPrintGrid);
			this.Controls.Add(this.tabControlAdv1);
			this.Controls.Add(this.gbxCheckinType);
			this.Name = "FormTestLabelInfo";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
			this.Text = "Test Label Info";
			this.Load += new System.EventHandler(this.FormTestLabelInfo_Load);
			this.gbxCheckinType.ResumeLayout(false);
			this.gbxCheckinType.PerformLayout();
			((System.ComponentModel.ISupportInitialize)(this.tabControlAdv1)).EndInit();
			this.tabControlAdv1.ResumeLayout(false);
			this.tab1.ResumeLayout(false);
			((System.ComponentModel.ISupportInitialize)(this.dgDraw)).EndInit();
			this.tab2.ResumeLayout(false);
			((System.ComponentModel.ISupportInitialize)(this.dgTestIn)).EndInit();
			this.tab3.ResumeLayout(false);
			((System.ComponentModel.ISupportInitialize)(this.dgTestOut)).EndInit();
			this.tab4.ResumeLayout(false);
			((System.ComponentModel.ISupportInitialize)(this.dgProtocol)).EndInit();
			this.tab5.ResumeLayout(false);
			((System.ComponentModel.ISupportInitialize)(this.dgPatient)).EndInit();
			this.ResumeLayout(false);

		}
		#endregion

		private void FormTestLabelInfo_Load(object sender, System.EventArgs e)
		{

		}


		private void btnPrintGrid_Click(object sender, System.EventArgs e)
		{
			Button button = (Button)sender;
			int indx = this.tabControlAdv1.SelectedIndex;
			_dgPrint = null;
			switch (indx)
			{
				case 0:
					_dgPrint = dgDraw;
					_subTitle = "Draw Info - Sample #: " + Num_ID.Text;
					break;
				case 1:
					_dgPrint = dgTestIn;
					_subTitle = "Test Check-in Info - Sample #: " + Num_ID.Text;
					break;
				case 2:
					_dgPrint = dgTestOut;
					_subTitle = "Test Check-out Info - Sample #: " + Num_ID.Text;
					break;
				case 3:
					_dgPrint = dgProtocol;
					_subTitle = "Protocol Info - Sample #: " + Num_ID.Text;
					break;
				case 4:
					_dgPrint = dgPatient;
					_subTitle = "Patient Info - Sample #: " + Num_ID.Text;
					break;

			}
			if (_dgPrint.DataSource == null)
			{
				MessageBox.Show("Nothing to print!");
				return;
			}
			_dtPrint = (DataTable)_dgPrint.DataSource;
			if (_dtPrint.Rows.Count == 0)
			{
				MessageBox.Show("Nothing to print!");
				return;
			}
			button.Enabled = false;

			this._pDoc = new PrintDocument();
			this._pDoc.DefaultPageSettings.Landscape = true;
			this._pDlg = new PrintDialog();
			this._pDlg.Document = this._pDoc;

			if (_pDlg.ShowDialog(this) == DialogResult.Cancel)
			{
				button.Enabled = true;
				return;
			}

			this._pDoc.PrintPage += new PrintPageEventHandler(_pDoc_PrintPage);
			_page = 1;
			_startRow = 0;
			this._pDoc.Print();

			button.Enabled = true;
		}

		private void _pDoc_PrintPage(object sender, PrintPageEventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			Graphics gfx = e.Graphics;
			float pageBottom = gfx.VisibleClipBounds.Height;
			float pageWidth = gfx.VisibleClipBounds.Width;
			float leftMargin = 25;
			float topMargin = 25;

			Font prntFont = new Font("Arial", 10);
			Font titleFont = new Font("Arial", 14, FontStyle.Bold);
			Font subTitleFont = new Font("Arial", 12);
			Font ColumnHeadFont = new Font("Arial", 10, FontStyle.Bold);

			Pen pen = new Pen(Color.Black);

			//get the line height with some padding
			float lineHeight = prntFont.GetHeight(e.Graphics) + 2;
			float adjLineHeight = 0;

			//set the drawing to the top left of the page
			float yPos = topMargin;
			float xPos = leftMargin;

			//print page #
			string page = "Page " + this._page;
			Forms.PrintingUtils.PrintCenter(page, e, prntFont, pageBottom - lineHeight);

			#region title
			StringBuilder sbCrit = new StringBuilder();

			//print title and subtitle
			if (this._page == 1)
			{
				Forms.PrintingUtils.PrintCenter(this._subTitle, e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			else
			{
				Forms.PrintingUtils.PrintCenter(this._subTitle, e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			yPos += lineHeight;
			#endregion title

			#region heading
			int[] colWidth = new int[this._dtPrint.Columns.Count];
			int[] colStart = new int[this._dtPrint.Columns.Count];
			int totWidth = 2;
			int i = 0;
			int width = 0;

			RectangleF rec = new RectangleF();
			gfx.DrawRectangle(Pens.Black, 0, yPos, (pageWidth - 25), lineHeight);
			gfx.FillRectangle(Brushes.LightBlue, 0, yPos, pageWidth - 25, lineHeight);

			foreach (DataColumn dc in this._dtPrint.Columns)
			{
				colStart[i] = totWidth + 2;

				width = Convert.ToInt32(dc.ExtendedProperties["Width"]);
				totWidth += width;
				colWidth[i] = width;

				Forms.PrintingUtils.SetRectangle(ref rec, colStart[i], yPos, lineHeight, colWidth[i]);
				gfx.DrawString(dc.Caption, ColumnHeadFont, Brushes.Black, rec);
				i++;
			}
			yPos += lineHeight;
			#endregion heading

			#region body
			//get the number of lines we can print
			int maxLines = (int)Math.Ceiling((double)((pageBottom - yPos) / lineHeight));
			maxLines -= 2;
			int curLine = 0;

			StringFormat fmt = new StringFormat();
			fmt.Trimming = StringTrimming.EllipsisCharacter;

			DataRow dr;
			int numLines = 0;
			for (int row = _startRow; row < _dtPrint.Rows.Count; row++)
			{
				dr = _dtPrint.Rows[row];

				//get the field with most number of lines
				numLines = PrintingUtils.GetNumberLinesRow(dr, e.Graphics, prntFont, lineHeight, colWidth);

				if (curLine + numLines >= maxLines)
				{
					_startRow = row;
					this._page++;
					e.HasMorePages = true;
					return;
				}

				adjLineHeight = lineHeight * numLines;
				int j = 0;
				string sVal = "";
				foreach (DataColumn dc in this._dtPrint.Columns)
				{
					Forms.PrintingUtils.SetRectangle(ref rec, colStart[j], yPos, adjLineHeight, colWidth[j]);
					switch (dc.DataType.ToString())
					{
						case "System.String":
							sVal = dr[dc.ColumnName].ToString().Trim();
							break;
						case "System.Int32":
							sVal = dr[dc.ColumnName].ToString();
							break;
						case "System.DateTime":
							sVal = ((DateTime)dr[dc.ColumnName]).ToString("MM/dd/yyyy");
							break;
						case "System.Decimal":
							sVal = ((decimal)dr[dc.ColumnName]).ToString("#,###.##");
							break;
						case "System.Boolean":
							sVal = dr[dc.ColumnName].ToString();
							break;
					}
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);
					j++;
				}

				gfx.DrawRectangle(Pens.Black, 0, yPos, (pageWidth - 25), adjLineHeight);
				yPos += adjLineHeight;
				curLine += numLines;
			}
			#endregion body
		}

		private void Retrieve_Click(object sender, System.EventArgs e)
		{
			if (Num_ID.Text.Length == 0)
				return;
			int id = int.Parse(Num_ID.Text);
			Retrieve.Enabled = false;
			GetDrawInfo(id);
			GetTestInInfo(id);
			GetTestOutInfo(id);
			GetProtocolInfo(id);
			GetPatientInfo(id);
			Retrieve.Enabled = true;
		}

		private void GetPatientInfo(int id)
		{
			dgPatient.DataSource = null;
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT p.ID AS [PatientID], p.MRN, p.OtherPatientID, " +
				"p.LastName + ',' + p.FirstName AS Name " +
				"FROM TestSamples t INNER JOIN DrawSamples d ON t.DrawSample = d.ID INNER JOIN " +
				"Patient p ON d.Patient = p.ID WHERE t.ID=" + id;

			//SqlConnection conn = LoginForm.GetSqlConnection();

			try
			{

				DataSet ds = DataAccess.GetDataSet(sql);
				DataTable dt = ds.Tables[0];

				DataColumn dc = dt.Columns["PatientID"];
				dc.Caption = "Pateint ID";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["MRN"];
				dc.Caption = "MRN";
				dc.ExtendedProperties.Add("Width", 120);

				dc = dt.Columns["OtherPatientID"];
				dc.Caption = "Alt ID";
				dc.ExtendedProperties.Add("Width", 150);

				dc = dt.Columns["Name"];
				dc.Caption = "Name";
				dc.ExtendedProperties.Add("Width", 150);

				dgPatient.DataSource = dt;

			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not display patient info.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this, sb.ToString(), "Display Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private void GetProtocolInfo(int id)
		{
			dgProtocol.DataSource = null;
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT p.SPID, p.ProtocolNumber, p.Title, " +
				"i.LastName + N',' + i.FirstName AS Investigator " +
				"FROM TestSamples t INNER JOIN " +
				"DrawSamples d ON t.DrawSample = d.ID INNER JOIN " +
				"Protocol p ON d.Protocol = p.ID INNER JOIN " +
				"ProtocolStaff ps ON d.Protocol = ps.ProtocolID INNER JOIN " +
				"Investigator i ON ps.InvestigatorID = i.ID " +
				"WHERE t.ID=" + id + " AND ps.StaffTypeID=1";
			//SqlConnection conn = LoginForm.GetSqlConnection();

			try
			{

				DataSet ds = DataAccess.GetDataSet(sql);
				DataTable dt = ds.Tables[0];

				DataColumn dc = dt.Columns["SPID"];
				dc.Caption = "SPID";
				dc.ExtendedProperties.Add("Width", 60);

				dc = dt.Columns["ProtocolNumber"];
				dc.Caption = "Protocol";
				dc.ExtendedProperties.Add("Width", 110);

				dc = dt.Columns["Title"];
				dc.Caption = "Title";
				dc.ExtendedProperties.Add("Width", 500);

				dc = dt.Columns["Investigator"];
				dc.Caption = "PI";
				dc.ExtendedProperties.Add("Width", 120);

				dgProtocol.DataSource = dt;

			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not display protocol info.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this, sb.ToString(), "Display Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private void GetTestOutInfo(int id)
		{
			dgTestOut.DataSource = null;
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT BatchOutNum FROM TestSamples WHERE ID=" + id;
			//SqlConnection conn = LoginForm.GetSqlConnection();

			try
			{
				object o = DataAccess.GetScalarObject(CommandType.Text, sql);
				if (o == null)
				{
					dgTestOut.Visible = false;
					return;
				}
				if (o == System.DBNull.Value)
				{
					dgTestOut.Visible = false;
					return;
				}

				dgTestOut.Visible = true;
				sql = "SELECT tt.Display AS Test, u.Display AS Unit, t.Result, t.OutDate, " +
					"t.OutTo, ot.Display AS Tester, t.BatchOutNum, ob.BatchOutDate, ob.CreatedBy " +
					"FROM TestSamples t INNER JOIN TestType_L tt ON t.TestType = tt.ID INNER JOIN " +
					"UnitOfMeasure_L u ON t.UnitOfMeasure = u.ID INNER JOIN " +
					"TestOutTo_L ot ON t.TestOutTo = ot.ID INNER JOIN " +
					"TestOutBatch ob ON t.BatchOutNum = ob.ID " +
					"WHERE t.ID=" + id;

				DataSet ds = DataAccess.GetDataSet(sql);
				DataTable dt = ds.Tables[0];

				DataColumn dc = dt.Columns["Test"];
				dc.Caption = "Test";
				dc.ExtendedProperties.Add("Width", 150);

				dc = dt.Columns["Unit"];
				dc.Caption = "Unit";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Result"];
				dc.Caption = "Result";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["OutDate"];
				dc.Caption = "Out Date";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["OutTo"];
				dc.Caption = "Out To";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Tester"];
				dc.Caption = "Tester";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["BatchOutNum"];
				dc.Caption = "Batch";
				dc.ExtendedProperties.Add("Width", 50);

				dc = dt.Columns["BatchOutDate"];
				dc.Caption = "Batch Date";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["CreatedBy"];
				dc.Caption = "By";
				dc.ExtendedProperties.Add("Width", 120);


				dgTestOut.DataSource = dt;

			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not display test check-out info.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this, sb.ToString(), "Display Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private void GetTestInInfo(int id)
		{
			dgTestIn.DataSource = null;
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT t.NotUsed, t.NoShow, t.Location, t.Note, t.SmallNote, " +
				"tt.Display AS Test, u.Display AS Unit, ib.ID AS BatchIn, ib.BatchInDate, ib.CreatedBy " +
				"FROM TestSamples t INNER JOIN TestType_L tt ON t.TestType = tt.ID INNER JOIN " +
				"UnitOfMeasure_L u ON t.UnitOfMeasure = u.ID INNER JOIN " +
				"TestInBatch ib ON t.BatchInNum = ib.ID " +
				"WHERE t.ID=" + id;
			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				DataSet ds = DataAccess.GetDataSet(sql);
				DataTable dt = ds.Tables[0];

				DataColumn dc = dt.Columns["NotUsed"];
				dc.Caption = "Not Used";
				dc.ExtendedProperties.Add("Width", 75);

				dc = dt.Columns["NoShow"];
				dc.Caption = "No Show";
				dc.ExtendedProperties.Add("Width", 75);

				dc = dt.Columns["Location"];
				dc.Caption = "Location";
				dc.ExtendedProperties.Add("Width", 130);

				dc = dt.Columns["Note"];
				dc.Caption = "Note";
				dc.ExtendedProperties.Add("Width", 150);

				dc = dt.Columns["SmallNote"];
				dc.Caption = "SmallNote";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Test"];
				dc.Caption = "Test";
				dc.ExtendedProperties.Add("Width", 150);

				dc = dt.Columns["Unit"];
				dc.Caption = "Unit";
				dc.ExtendedProperties.Add("Width", 60);

				dc = dt.Columns["BatchIn"];
				dc.Caption = "Batch";
				dc.ExtendedProperties.Add("Width", 50);

				dc = dt.Columns["BatchInDate"];
				dc.Caption = "Batch Date";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["CreatedBy"];
				dc.Caption = "By";
				dc.ExtendedProperties.Add("Width", 120);

				dgTestIn.DataSource = dt;

			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not display test check-in info.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this, sb.ToString(), "Display Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private void GetDrawInfo(int id)
		{
			dgDraw.DataSource = null;
			StringBuilder sb = new StringBuilder();
			//if batchinnum = 0 then this is a legacy
			string sql = "SELECT d.BatchInNum FROM TestSamples t INNER JOIN " +
				" DrawSamples d ON t.DrawSample = d.ID WHERE t.ID=" + id;

			//SqlConnection conn = LoginForm.GetSqlConnection();


			try
			{
				int batch = (int)DataAccess.GetScalarObject(CommandType.Text, sql);
				if (batch == 0)
				{
					sql = "SELECT  d.ID, p.SPID AS SPID, p.ProtocolNumber, d.Patient, d.VisitDate, " +
						"d.Visit, d.VisitTime, s.Display AS Sample, d.BatchInNum " +
						"FROM TestSamples t INNER JOIN DrawSamples d ON t.DrawSample = d.ID INNER JOIN " +
						"SampleType_L s ON d.SampleType = s.ID INNER JOIN  Protocol p ON d.Protocol = p.ID " +
						"WHERE t.ID=" + id;
				}
				else
				{
					sql = "SELECT  d.ID, p.SPID AS SPID, p.ProtocolNumber, d.Patient, d.VisitDate, " +
						"d.Visit, d.VisitTime, s.Display AS Sample, b.ID AS BatchInNum, b.BatchDate, b.CreatedBy " +
						"FROM TestSamples t INNER JOIN DrawSamples d ON t.DrawSample = d.ID INNER JOIN " +
						"SampleType_L s ON d.SampleType = s.ID INNER JOIN DrawBatch b ON d.BatchInNum = b.ID " +
						"INNER JOIN Protocol p ON d.Protocol = p.ID " +
						"WHERE t.ID=" + id;
				}

				DataSet ds = DataAccess.GetDataSet(sql);
				DataTable dt = ds.Tables[0];
				DataColumn dc = dt.Columns["ID"];
				dc.Caption = "Draw ID";
				dc.ExtendedProperties.Add("Width", 60);

				dc = dt.Columns["SPID"];
				dc.Caption = "SPID";
				dc.ExtendedProperties.Add("Width", 60);

				dc = dt.Columns["ProtocolNumber"];
				dc.Caption = "Protocol";
				dc.ExtendedProperties.Add("Width", 110);

				dc = dt.Columns["Patient"];
				dc.Caption = "Patient";
				dc.ExtendedProperties.Add("Width", 60);

				dc = dt.Columns["VisitDate"];
				dc.Caption = "Visit Date";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["Visit"];
				dc.Caption = "Visit";
				dc.ExtendedProperties.Add("Width", 100);

				dc = dt.Columns["VisitTime"];
				dc.Caption = "Time";
				dc.ExtendedProperties.Add("Width", 50);

				dc = dt.Columns["Sample"];
				dc.Caption = "Sample";
				dc.ExtendedProperties.Add("Width", 150);

				dc = dt.Columns["BatchInNum"];
				dc.Caption = "Batch";
				dc.ExtendedProperties.Add("Width", 50);

				if (batch > 0)
				{
					dc = dt.Columns["BatchDate"];
					dc.Caption = "Batch Date";
					dc.ExtendedProperties.Add("Width", 100);

					dc = dt.Columns["CreatedBy"];
					dc.Caption = "By";
					dc.ExtendedProperties.Add("Width", 120);
				}

				dgDraw.DataSource = dt;

			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not display draw info.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this, sb.ToString(), "Display Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private void btnExit_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}


	}
}
